

package com.ruoyi.activiti.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.util.StringUtil;
import com.ruoyi.activiti.domain.ActRuIdentitylink;
import com.ruoyi.activiti.domain.ActWorkflowFormData;
import com.ruoyi.activiti.domain.dto.ActTaskDTO;
import com.ruoyi.activiti.domain.dto.ActWorkflowFormDataDTO;
import com.ruoyi.activiti.domain.vo.SearchVo;
import com.ruoyi.activiti.mapper.ActRuIdentitylinkMapper;
import com.ruoyi.activiti.mapper.ActWorkflowFormDataMapper;
import com.ruoyi.activiti.service.IActTaskService;
import com.ruoyi.activiti.service.IActWorkflowFormDataService;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.exception.BaseException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.EmailUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.AsposeUtil;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.system.mapper.SysPostMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.activiti.api.runtime.shared.NotFoundException;
import org.activiti.api.runtime.shared.query.Pageable;
import org.activiti.api.task.model.Task;
import org.activiti.api.task.model.builders.TaskPayloadBuilder;
import org.activiti.api.task.runtime.TaskRuntime;
import org.activiti.bpmn.model.FormProperty;
import org.activiti.bpmn.model.UserTask;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricDetail;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricVariableUpdate;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.TaskQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
@Slf4j
public class ActTaskServiceImpl implements IActTaskService {

    @Autowired
    private RepositoryService repositoryService;

    @Resource
    private TaskService taskService;

    @Autowired
    private TaskRuntime taskRuntime;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private IActWorkflowFormDataService actWorkflowFormDataService;

    @Autowired
    private HistoryService historyService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ServerConfig serverConfig;

    @Value("${spring.mail.from}") // 从application.yml配置文件中获取
    private String from; //  发送发邮箱地址

    @Value("${uat.url}") // 从application.yml配置文件中获取
    private String url; //  网址

    @Value("${uat.msg}") // 从application.yml配置文件中获取
    private String msg; //  网址

    @Value("${uat.isSendEmal}") // 从application.yml配置文件中获取
    private String isSendEmal; //  网址

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private ActRuIdentitylinkMapper actRuIdentitylinkMapper;

    @Autowired
    private SysPostMapper sysPostMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private ActWorkflowFormDataMapper actWorkflowFormDataMapper;


    @Override
    public Page<ActTaskDTO> selectProcessDefinitionList(PageDomain pageDomain) {
        Page<ActTaskDTO> list = new Page<ActTaskDTO>();
        org.activiti.api.runtime.shared.query.Page<Task> pageTasks = taskRuntime.tasks(Pageable.of((pageDomain.getPageNum() - 1) * pageDomain.getPageSize(), pageDomain.getPageSize()));
        List<Task> tasks = pageTasks.getContent();
        int totalItems = pageTasks.getTotalItems();
        list.setTotal(totalItems);
        if (totalItems != 0) {
            Set<String> processInstanceIdIds = tasks.parallelStream()
                    .map(t -> t.getProcessInstanceId())
                    .collect(Collectors.toSet());
            List<ProcessInstance> processInstanceList = runtimeService.createProcessInstanceQuery()
                    .processInstanceIds(processInstanceIdIds)
                    .list();
            System.out.println("processInstanceList==" + processInstanceList.toString());
            List<ActTaskDTO> actTaskDTOS = tasks.stream()
                    .map(t -> new ActTaskDTO(t, processInstanceList.parallelStream()
                            .filter(pi -> t.getProcessInstanceId()
                                    .equals(pi.getId()))
                            .findAny()
                            .get()))
                    .collect(Collectors.toList());
            System.out.println("actTaskDTOS==" + actTaskDTOS.toString());
            list.addAll(actTaskDTOS);

        }
        System.out.println("获取到的结果集==" + list.toString());
        return list;
    }

    //获取已办列表
    @Override
    public Page<ActTaskDTO> selectProcessDefinitionHandleList(PageDomain pageDomain) {
        Page<ActTaskDTO> list = new Page<ActTaskDTO>();
        org.activiti.api.runtime.shared.query.Page<Task> pageTasks = taskRuntime.tasks(Pageable.of((pageDomain.getPageNum() - 1) * pageDomain.getPageSize(), pageDomain.getPageSize()));
        List<Task> tasks = pageTasks.getContent();
        int totalItems = pageTasks.getTotalItems();
        list.setTotal(totalItems);
        if (totalItems != 0) {
            Set<String> processInstanceIdIds = tasks.parallelStream()
                    .map(t -> t.getProcessInstanceId())
                    .collect(Collectors.toSet());
            List<ProcessInstance> processInstanceList = runtimeService.createProcessInstanceQuery()
                    .processInstanceIds(processInstanceIdIds)
                    .list();
            List<ActTaskDTO> actTaskDTOS = tasks.stream()
                    .map(t -> new ActTaskDTO(t, processInstanceList.parallelStream()
                            .filter(pi -> t.getProcessInstanceId()
                                    .equals(pi.getId()))
                            .findAny()
                            .get()))
                    .collect(Collectors.toList());
            list.addAll(actTaskDTOS);

        }
        return list;
    }

    //根据条件搜索
    @Override
    public Page<ActTaskDTO> selectProcessDefinitionSearchList(SearchVo searchVo, PageDomain pageDomain) {
        pageDomain.setPageNum(1);
        pageDomain.setPageSize(20);
        Page<ActTaskDTO> list = new Page<ActTaskDTO>();
        // org.activiti.api.runtime.shared.query.Page<Task> pageTasks = taskRuntime.tasks(Pageable.of((pageDomain.getPageNum() - 1) * pageDomain.getPageSize(), pageDomain.getPageSize()));
        org.activiti.api.runtime.shared.query.Page<Task> pageTasks = taskRuntime.tasks(Pageable.of(0, 10));

        List<Task> tasks = pageTasks.getContent();
        int totalItems = pageTasks.getTotalItems();
        System.out.println("tasks==" + tasks.toString());
        //tasks==[TaskImpl{id='0ae97a6b-fd10-11ec-926c-60f26273afc4', owner='null', assignee='null', name='信审勾选填写两个问题', description='null', createdDate=Wed Jul 06 17:43:08 CST 2022, claimedDate=null, dueDate=null, priority=50, processDefinitionId='Process_a:1:425e7506-fcd6-11ec-a3fa-60f26273afc4', processInstanceId='0ae95357-fd10-11ec-926c-60f26273afc4', parentTaskId='null', formKey='null', status=CREATED, processDefinitionVersion=null, businessKey=null}, TaskImpl{id='2111e147-00d4-11ed-af01-005056c00008', owner='null', assignee='null', name='RM', description='null', createdDate=Mon Jul 11 12:44:20 CST 2022, claimedDate=null, dueDate=null, priority=50, processDefinitionId='Process_a:3:c7084174-fdce-11ec-8bfc-60f26273afc4', processInstanceId='21058533-00d4-11ed-af01-005056c00008', parentTaskId='null', formKey='Activity_1hrzbia', status=CREATED, processDefinitionVersion=null, businessKey=null}, TaskImpl{id='34972e69-01d8-11ed-b55f-005056c00008', owner='null', assignee='null', name='RM', description='null', createdDate=Tue Jul 12 19:46:02 CST 2022, claimedDate=null, dueDate=null, priority=50, processDefinitionId='annualVerification:2:559720dd-01d6-11ed-8ad6-005056c00008', processInstanceId='348fb455-01d8-11ed-b55f-005056c00008', parentTaskId='null', formKey='Activity_1hrzbia', status=CREATED, processDefinitionVersion=null, businessKey=null}, TaskImpl{id='37042e6f-00fd-11ed-8e56-005056c00008', owner='null', assignee='null', name='RM', description='null', createdDate=Mon Jul 11 17:38:26 CST 2022, claimedDate=null, dueDate=null, priority=50, processDefinitionId='Process_a:3:c7084174-fdce-11ec-8bfc-60f26273afc4', processInstanceId='36fd298b-00fd-11ed-8e56-005056c00008', parentTaskId='null', formKey='Activity_1hrzbia', status=CREATED, processDefinitionVersion=null, businessKey=null}, TaskImpl{id='373fdc70-fd22-11ec-926c-60f26273afc4', owner='null', assignee='null', name='信审勾选填写两个问题', description='null', createdDate=Wed Jul 06 19:53:13 CST 2022, claimedDate=null, dueDate=null, priority=50, processDefinitionId='Process_a:2:d46b6825-fd12-11ec-926c-60f26273afc4', processInstanceId='373fb55c-fd22-11ec-926c-60f26273afc4', parentTaskId='null', formKey='Activity_1hrzbia', status=CREATED, processDefinitionVersion=null, businessKey=null}, TaskImpl{id='423e044c-0354-11ed-ad6c-005056c00008', owner='null', assignee='null', name='部门领导审批', description='null', createdDate=Thu Jul 14 17:06:34 CST 2022, claimedDate=null, dueDate=null, priority=50, processDefinitionId='leave:1:d437a1dd-f5c9-11ec-ad82-60f26273afc4', processInstanceId='423d6806-0354-11ed-ad6c-005056c00008', parentTaskId='null', formKey='deptLeaderVerify', status=CREATED, processDefinitionVersion=null, businessKey=null}, TaskImpl{id='6a946ed6-fcdc-11ec-a3fa-60f26273afc4', owner='null', assignee='null', name='部门领导审批', description='null', createdDate=Wed Jul 06 11:33:35 CST 2022, claimedDate=null, dueDate=null, priority=50, processDefinitionId='leave:1:d437a1dd-f5c9-11ec-ad82-60f26273afc4', processInstanceId='6a93d28b-fcdc-11ec-a3fa-60f26273afc4', parentTaskId='null', formKey='deptLeaderVerify', status=CREATED, processDefinitionVersion=null, businessKey=null}, TaskImpl{id='6a946ed7-fcdc-11ec-a3fa-60f26273afc4', owner='null', assignee='null', name='部门领导审批', description='null', createdDate=Wed Jul 06 11:33:35 CST 2022, claimedDate=null, dueDate=null, priority=50, processDefinitionId='leave:1:d437a1dd-f5c9-11ec-ad82-60f26273afc4', processInstanceId='6a93d28a-fcdc-11ec-a3fa-60f26273afc4', parentTaskId='null', formKey='deptLeaderVerify', status=CREATED, processDefinitionVersion=null, businessKey=null}, TaskImpl{id='91632331-fd10-11ec-926c-60f26273afc4', owner='null', assignee='null', name='信审勾选填写两个问题', description='null', createdDate=Wed Jul 06 17:46:54 CST 2022, claimedDate=null, dueDate=null, priority=50, processDefinitionId='Process_a:1:425e7506-fcd6-11ec-a3fa-60f26273afc4', processInstanceId='9162fc1d-fd10-11ec-926c-60f26273afc4', parentTaskId='null', formKey='null', status=CREATED, processDefinitionVersion=null, businessKey=null}, TaskImpl{id='b2fb3f6f-0315-11ed-ad6c-005056c00008', owner='null', assignee='null', name='部门领导审批', description='null', createdDate=Thu Jul 14 09:38:45 CST 2022, claimedDate=null, dueDate=null, priority=50, processDefinitionId='leave:1:d437a1dd-f5c9-11ec-ad82-60f26273afc4', processInstanceId='b2f43a89-0315-11ed-ad6c-005056c00008', parentTaskId='null', formKey='deptLeaderVerify', status=CREATED, processDefinitionVersion=null, businessKey=null}, TaskImpl{id='b8557e6f-fd0f-11ec-926c-60f26273afc4', owner='null', assignee='null', name='信审勾选填写两个问题', description='null', createdDate=Wed Jul 06 17:40:50 CST 2022, claimedDate=null, dueDate=null, priority=50, processDefinitionId='Process_a:1:425e7506-fcd6-11ec-a3fa-60f26273afc4', processInstanceId='b850c37b-fd0f-11ec-926c-60f26273afc4', parentTaskId='null', formKey='null', status=CREATED, processDefinitionVersion=null, businessKey=null}, TaskImpl{id='c7bde62f-024a-11ed-914d-005056c00008', owner='null', assignee='null', name='RM', description='null', createdDate=Wed Jul 13 09:26:11 CST 2022, claimedDate=null, dueDate=null, priority=50, processDefinitionId='annualVerification:2:559720dd-01d6-11ed-8ad6-005056c00008', processInstanceId='c7b581bb-024a-11ed-914d-005056c00008', parentTaskId='null', formKey='Activity_1hrzbia', status=CREATED, processDefinitionVersion=null, businessKey=null}, TaskImpl{id='cf1ef7a0-0419-11ed-aabc-005056c00008', owner='null', assignee='null', name='RM', description='null', createdDate=Fri Jul 15 16:40:41 CST 2022, claimedDate=null, dueDate=null, priority=50, processDefinitionId='annualVerification:2:559720dd-01d6-11ed-8ad6-005056c00008', processInstanceId='cf11630c-0419-11ed-aabc-005056c00008', parentTaskId='null', formKey='Activity_1hrzbia', status=CREATED, processDefinitionVersion=null, businessKey=null}, TaskImpl{id='ede1d665-fd0f-11ec-926c-60f26273afc4', owner='null', assignee='null', name='信审勾选填写两个问题', description='null', createdDate=Wed Jul 06 17:42:19 CST 2022, claimedDate=null, dueDate=null, priority=50, processDefinitionId='Process_a:1:425e7506-fcd6-11ec-a3fa-60f26273afc4', processInstanceId='ede1d661-fd0f-11ec-926c-60f26273afc4', parentTaskId='null', formKey='null', status=CREATED, processDefinitionVersion=null, businessKey=null}, TaskImpl{id='ee71957d-00e7-11ed-8dc0-005056c00008', owner='null', assignee='null', name='RM', description='null', createdDate=Mon Jul 11 15:06:05 CST 2022, claimedDate=null, dueDate=null, priority=50, processDefinitionId='Process_a:3:c7084174-fdce-11ec-8bfc-60f26273afc4', processInstanceId='ee6c1739-00e7-11ed-8dc0-005056c00008', parentTaskId='null', formKey='Activity_1hrzbia', status=CREATED, processDefinitionVersion=null, businessKey=null}]

        TaskQuery taskQuery = taskService.createTaskQuery();
        if (StringUtils.isNotBlank(searchVo.getProcessName())) {
            taskQuery.taskNameLike("%" + searchVo.getProcessName() + "%");
        }
        if (searchVo.getStartDate() != null) {
            taskQuery.taskCreatedAfter(searchVo.getStartDate());
        }
        if (searchVo.getEndDate() != null) {
            taskQuery.taskCreatedBefore(searchVo.getEndDate());
        }
        if(StringUtils.isNotBlank(searchVo.getBusinessKey())){
            taskQuery.processInstanceBusinessKeyLikeIgnoreCase(searchVo.getBusinessKey());
        }
        // taskQuery.processDefinitionKey("Process_a");
        // List<Task> taskList = taskQuery.listPage(pageDomain.getPageNum(), pageDomain.getPageSize());
        List<org.activiti.engine.task.Task> taskList = taskQuery
                // .taskNameLike("%" + searchVo.getProcessName() + "%")
                // .taskCreatedAfter(searchVo.getStartDate())
                // .taskCreatedBefore(searchVo.getEndDate())
                .list();
        System.out.println("taskList===" + taskList.toString());

        if (totalItems != 0) {
            // List<ActTaskDTO> actTaskDTOS = new ArrayList<>();
            for (Task task : tasks) {
                Set<String> processInstanceIdIds = taskList.parallelStream()
                        .map(t -> t.getProcessInstanceId())
                        .collect(Collectors.toSet());
                System.out.println("processInstanceIdIds===" + processInstanceIdIds.toString());
                //processInstanceIdIds===[cf11630c-0419-11ed-aabc-005056c00008, ee6c1739-00e7-11ed-8dc0-005056c00008, 36fd298b-00fd-11ed-8e56-005056c00008, c7b581bb-024a-11ed-914d-005056c00008, 21058533-00d4-11ed-af01-005056c00008, 348fb455-01d8-11ed-b55f-005056c00008]
                List<ProcessInstance> processInstanceList = runtimeService.createProcessInstanceQuery()
                        .processInstanceIds(processInstanceIdIds)
                        .list();
                System.out.println("processInstanceList===" + processInstanceList.toString());
                //processInstanceList===[ProcessInstance[21058533-00d4-11ed-af01-005056c00008], ProcessInstance[348fb455-01d8-11ed-b55f-005056c00008], ProcessInstance[36fd298b-00fd-11ed-8e56-005056c00008], ProcessInstance[c7b581bb-024a-11ed-914d-005056c00008], ProcessInstance[cf11630c-0419-11ed-aabc-005056c00008], ProcessInstance[ee6c1739-00e7-11ed-8dc0-005056c00008]]
                List<ActTaskDTO> actTaskDTOS = tasks.stream()
                        .map(t -> new ActTaskDTO(t, processInstanceList.parallelStream()
                                .filter(pi -> t.getProcessInstanceId()
                                        .equals(pi.getId()))
                                .findAny()
                                .get()))
                        .collect(Collectors.toList());
                System.out.println("actTaskDTOS===" + actTaskDTOS.toString());
                // ActTaskDTO actTaskDTO = new ActTaskDTO();
                // actTaskDTO.setId(task.getId());
                // actTaskDTO.setName(task.getName());
                // actTaskDTO.setStatus(task.getDelegationState().toString());
                // actTaskDTO.setCreatedDate(task.getCreateTime());
                // actTaskDTO.setInstanceName(task.na());
                // actTaskDTO.setDefinitionKey(task.getTaskDefinitionKey());
                // actTaskDTO.setBusinessKey(task.());

                // {
                //     "params": {},
                //     "id": "2111e147-00d4-11ed-af01-005056c00008",
                //         "name": "RM",
                //         "status": "CREATED",
                //         "createdDate": "2022-07-11 12:44:20",
                //         "instanceName": "若依的授信",
                //         "definitionKey": "Process_a",
                //         "businessKey": "7154f7ce27674565b19264c2c01deab7"
                // },

                list.addAll(actTaskDTOS);
            }
        }

        // list.addAll(tasks);
        // list.addAll((Collection<? extends ActTaskDTO>) taskss);

        return list;
    }

    @Override
    public List<String> formDataShow(String taskID) {
        try{
            Task task = taskRuntime.task(taskID);
        }catch (NotFoundException e){
            throw  new BaseException("该流程已关闭");
        }
        Task task = taskRuntime.task(taskID);
/*  ------------------------------------------------------------------------------
            FormProperty_0ueitp2--__!!类型--__!!名称--__!!是否参数--__!!默认值
            例子：
            FormProperty_0lovri0--__!!string--__!!姓名--__!!f--__!!同意!!__--驳回
            FormProperty_1iu6onu--__!!int--__!!年龄--__!!s

            默认值：无、字符常量、FormProperty_开头定义过的控件ID
            是否参数：f为不是参数，s是字符，t是时间(不需要int，因为这里int等价于string)
            注：类型是可以获取到的，但是为了统一配置原则，都配置到
            */

        //注意!!!!!!!!:表单Key必须要任务编号一模一样，因为参数需要任务key，但是无法获取，只能获取表单key“task.getFormKey()”当做任务key
        UserTask userTask = (UserTask) repositoryService.getBpmnModel(task.getProcessDefinitionId())
                .getFlowElement(task.getFormKey());

        if (userTask == null) {
            return null;
        }
        List<FormProperty> formProperties = userTask.getFormProperties();
        List<String> collect = formProperties.stream()
                .map(fp -> fp.getId())
                .collect(Collectors.toList());
        ArrayList<String> list = new ArrayList<>();
        for (String s : collect) {
            if(s.contains("FormProperty_1vn4m79") ||  s.contains("FormProperty_0p5118h")
                    ||  s.contains("FormProperty_1lnclmq")
                    ||  s.contains("FormProperty_0a566om")
                    ||  s.contains("FormProperty_05hiprb")
                    ||  s.contains("FormProperty_138sqb4")
            ){
                String replace = s.replace("--__--作废", "");
                list.add(replace);
            }else{
                list.add(s);
            }
        }

        return list;
    }

    @Override
    public int formDataSave(String taskID, List<ActWorkflowFormDataDTO> awfs) throws ParseException {
        //判断该流程是否加锁
        String uuid = IdUtils.get16UUID();
  /*      ProcessInstance processInstance1 = runtimeService.createProcessInstanceQuery().processInstanceId(taskID).singleResult();
        if(processInstance1 ==null){
            throw new BaseException("改流程已关闭");
        }*/
        boolean shouDong = false;
        for (ActWorkflowFormDataDTO awf : awfs) {
            if(awf.getFlag() !=null ){
                if(awf.getFlag().equals("1")){
                    shouDong = true ;
                    break;
                }
            }

        }

        if(shouDong){
            //转派
            taskService.unclaim(taskID);
            taskService.claim(taskID, SecurityUtils.getUsername());
        }

        String dqjdmc ="";
        ArrayList<String> nodeNameList = new ArrayList<>();
        try{
            actWorkflowFormDataMapper.insertActWorkflowLock(uuid,taskID);
        }catch (Exception e) {
            e.printStackTrace();
            Throwable cause = e.getCause();
            if (cause instanceof java.sql.SQLIntegrityConstraintViolationException) {
                //错误信息
                String errMsg = ((java.sql.SQLIntegrityConstraintViolationException) cause).getMessage();
                //根据约束名称定位是那个字段
                if (StringUtils.isNotBlank(errMsg) && errMsg.indexOf("ux_task_id") != -1) {
                    throw  new BaseException("该流程已锁定,请稍后");
                } else {
                    throw  new BaseException("该流程已锁定,请稍后");
                }
            } else {
                throw  new BaseException("该流程已锁定,请稍后");
            }
        }

        try {
            try {
                Task task = taskRuntime.task(taskID);
                dqjdmc = task.getName();
                ProcessInstance processInstanceTemp = runtimeService.createProcessInstanceQuery()
                        .processInstanceId(task.getProcessInstanceId())
                        .singleResult();
                List<org.activiti.engine.task.Task> listTask = taskService.createTaskQuery()
                        .processInstanceId(processInstanceTemp.getProcessInstanceId())
                        .list();
                if(listTask.size()>1){
                    for (org.activiti.engine.task.Task task1 : listTask) {
                        System.out.println("当前节点是几个呢"+task1.getName());
                        nodeNameList.add(task1.getName());
                    }
                }
                System.out.println("当前节点名称是:"+dqjdmc);
            } catch (NotFoundException e) {
                throw new BaseException("该流程已关闭");
                //切换用户
            }

            Task task = taskRuntime.task(taskID);
            HashMap<String, Object> variables = new HashMap<String, Object>();
            Boolean hasVariables = false;//没有任何参数
            Boolean flag = false;
            Boolean flag1 = false;
            Boolean flag2 = false;
            Boolean flag3 = false;
            String businessKey = "";
            BigDecimal GAP = null;
            BigDecimal TOTAL =  null;
            List<HistoricProcessInstance> list1 = historyService.createHistoricProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).list();
            if (CollectionUtil.isNotEmpty(list1)) {
                businessKey = list1.get(0).getBusinessKey();
            }
            //TODO 根据流程合同所属经销商制定DM用户
            //根据经销商名称转发指定dm用户
            if ("Activity_1jixivt".equals(task.getFormKey()) || "Activity_0djncal".equals(task.getFormKey()) || "Activity_1do0hn0".equals(task.getFormKey())
                    || "Activity_1y4oxv8".equals(task.getFormKey())) {
                ArrayList<String> strings = new ArrayList<>();

                ArrayList<SysUser> users = new ArrayList<>();

//                List<String> dealerNameByInstId = actWorkflowFormDataMapper.getDealerNameBySubProcessId(businessKey);
//                for (String dealerName : dealerNameByInstId) {
//                    String dmName = actWorkflowFormDataMapper.getDmByDealerName(dealerName);
//                    SysUser sysUser = sysUserMapper.selectUserByNickName(dmName);
//                    users.add(sysUser);
//
//                    //sendMailByEmailInfo(sysUser,businessKey,false);
//
//                }
//
//                if(users.size() > 0){
//                    //存在映射
//                    for (SysUser user : users) {
//                        strings.add(user.getUserName());
//                        variables.put("SelectDm", StringUtils.join(strings, ","));
//                        sendMailByEmailInfo(user,businessKey,false);
//
//                    }
//
//                }else {                }

                String instanceId = actWorkflowFormDataMapper.getInstanceIdBySubProcessId(businessKey);
                String createBy = actWorkflowFormDataMapper.getCreateBy(instanceId);
                if(StringUtils.isNotEmpty(createBy) && createBy.equals("AF569")){
                    createBy = "af504";
                }

                //子流程dm节点办理人发送待办邮件
                //sendMailByEmailInfo(sysUserMapper.selectUserByUserName(createBy),businessKey,false);

                variables.put("SelectDm",createBy);



                //variables.put("SelectDm", StringUtils.join(strings, ","));

                hasVariables = true;
            }else {
                variables.put("SelectDm","");
            }



            if ("Activity_1j9b1pe".equals(task.getFormKey())) {
                //流程9
                Map<String, Object> annualReviewy = actWorkflowFormDataMapper.getAnnualReviewyByInstanceId(businessKey);
                GAP = new BigDecimal(annualReviewy.get("GAP").toString());
                TOTAL = new BigDecimal(annualReviewy.get("TOTAL").toString());
                if (GAP != null && TOTAL != null) {
                    variables.put("GPA",  GAP.longValue());
                    variables.put("TOTAL",  TOTAL.longValue());
                    variables.put("FormProperty_0nfqek9", 0);
                } else {
                    throw new BaseException("该流程GPA为空,TOTAL为空,请检查");
                }
            }


            if ("Activity_1hw7ebl".equals(task.getFormKey())) {
                variables.put("toUnderwriter", 0);
                hasVariables = true;
                // 查找上一个已完成的user task节点
                List<HistoricDetail> list = historyService.createHistoricDetailQuery()
                        .processInstanceId(task.getProcessInstanceId())
                        .orderByTime()
                        .desc()
                        .list();
                String tmpTaskId = "";
                for (HistoricDetail detail : list) {
                    if (!"".equals(tmpTaskId) && !tmpTaskId.equals(detail.getTaskId())) {
                        break;
                    } else if (detail.getTaskId() == null) {
                        continue;
                    } else {
                        tmpTaskId = detail.getTaskId();
                    }
                    HistoricVariableUpdate historicVariableUpdate = (HistoricVariableUpdate) detail;
                    if ("FormProperty_1g5r6sp".equals(historicVariableUpdate.getVariableName())) {
                        if (2 == Integer.valueOf(String.valueOf(historicVariableUpdate.getValue()))) {
                            variables.put("toUnderwriter", 1);
                            hasVariables = true;
                        }
                        break;
                    }
                }
            }

            ProcessInstance processInstance = runtimeService.createProcessInstanceQuery()
                    .processInstanceId(task.getProcessInstanceId())
                    .singleResult();


            //前端传来的字符串，拆分成每个控件
            List<ActWorkflowFormData> acwfds = new ArrayList<>();
            for (ActWorkflowFormDataDTO awf : awfs) {
                ActWorkflowFormData actWorkflowFormData = new ActWorkflowFormData(processInstance.getBusinessKey(), awf, task);
                if(StringUtils.isNotEmpty(awf.getApprovalPost())){
                    actWorkflowFormData.setApprovalPost(awf.getApprovalPost());
                }
                acwfds.add(actWorkflowFormData);
                //构建参数集合
                if (!"f".equals(awf.getControlIsParam())) {
                    if (null != awf.getControlValue()) {
                        variables.put(awf.getControlId(), awf.getControlValue());
                        hasVariables = true;
                    }
                }
                // if("dmSelect".equals(awf.getControlId())) {
                //     variables.put(awf.getControlId(), awf.getControlValue());
                //     hasVariables = true;
                // }
            }//for结束
            if ("Activity_1vev1yp".equals(task.getFormKey())) {
                int count = actWorkflowFormDataMapper.getProcessByInstanceId(businessKey);
                Object FormProperty_0kgarqo = variables.get("FormProperty_0kgarqo");
                if(((String) FormProperty_0kgarqo).equals("0")){
                    variables.put("FormProperty_0kgarqo", 2);
                }
                if(count>0 && ((String) FormProperty_0kgarqo).equals("0")){
                    variables.put("FormProperty_0kgarqo", 3);
                }
            }
            HashMap<String, Object> variables1 = new HashMap<String, Object>();
            if ("Activity_11mvezs".equals(task.getFormKey())) {
                if (variables != null) {
                    //判断是否是op拒绝
                    Object formProperty_1lnclmq = variables.get("FormProperty_1lnclmq");
                    if (formProperty_1lnclmq != null) {
                        if (((String) formProperty_1lnclmq).equals("1")) {
                            actRuIdentitylinkMapper.updateActRuVariableByTaskId(task.getProcessInstanceId(),"FormProperty_0e6rhg9");
                            //拒绝
                            flag = true;
                            variables1.put("FormProperty_0a566om",1);
                            variables1.put("FormProperty_0e6rhg9",0);
                            variables1.put("FormProperty_1lnclmq",1);
                        }else{
                            actRuIdentitylinkMapper.updateActRuVariableByTaskId(task.getProcessInstanceId(),"FormProperty_1lnclmq");
                        }
                    }
                }
            }
            if ("Activity_1y4oxv8".equals(task.getFormKey())) {
                if(variables != null){
                    Object FormProperty_0onpemn = variables.get("FormProperty_0onpemn");
                    if (FormProperty_0onpemn != null) {
                        if (((String) FormProperty_0onpemn).equals("2")) {
                            flag3 =true;
                        }
                    }
                }

            }
            if ("Activity_0yzduiw".equals(task.getFormKey())) {
                if(variables != null){
                    Object FormProperty_0onpemn = variables.get("FormProperty_0onpemn");
                    if (FormProperty_0onpemn != null) {
                        if (((String) FormProperty_0onpemn).equals("2")) {
                            flag3 =true;
                        }
                    }
                }

            }

            if ("Activity_1ei1y8i".equals(task.getFormKey())) {
                if (variables != null) {
                    //判断是否是op拒绝
                    Object FormProperty_0a566om = variables.get("FormProperty_0a566om");
                    if (FormProperty_0a566om != null) {
                        if (((String) FormProperty_0a566om).equals("1")) {
                            actRuIdentitylinkMapper.updateActRuVariableByTaskId(task.getProcessInstanceId(),"FormProperty_0e6rhg9");

                            //拒绝
                            flag1 = true;
                            variables1.put("FormProperty_0a566om",1);
                            variables1.put("FormProperty_1lnclmq",1);
                            variables1.put("FormProperty_0e6rhg9",0);
                        }else if (((String) FormProperty_0a566om).equals("2")){
                            if(nodeNameList.size()>1  &&  nodeNameList.contains("保证金调整审核")){
                                throw new BaseException("该流程保证金调整确认已通过审批，不允许作废!");
                            }
                        }else{
                            actRuIdentitylinkMapper.updateActRuVariableByTaskId(task.getProcessInstanceId(),"FormProperty_0a566om");
                        }
                    }
                }
            }
/*            if ("Activity_1asn37d".equals(task.getFormKey())) {
                if (variables != null) {
                    //判断是否是op拒绝
                    Object FormProperty_0e6rhg9 = variables.get("FormProperty_0e6rhg9");
                    if (FormProperty_0e6rhg9 != null) {
                        if (((String) FormProperty_0e6rhg9).equals("1")) {
                            actRuIdentitylinkMapper.updateActRuVariableByTaskId(task.getProcessInstanceId(),"FormProperty_0e6rhg9");

                            //拒绝
                            flag2 = true;
                            variables1.put("FormProperty_0a566om",1);
                            variables1.put("FormProperty_1lnclmq",1);
                            variables1.put("FormProperty_0e6rhg9",0);
                        }else{
                            actRuIdentitylinkMapper.updateActRuVariableByTaskId(task.getProcessInstanceId(),"FormProperty_0e6rhg9");
                        }
                    }
                }
            }*/

            if (task.getAssignee() == null) {
                taskRuntime.claim(TaskPayloadBuilder.claim()
                        .withTaskId(task.getId())
                        .build());
            }

            List<String> uwUserNames = sysUserMapper.getuwNamesByPostCode("underwriter");

            List<org.activiti.engine.task.Task> listTaskXs = taskService.createTaskQuery()
                    .processInstanceId(processInstance.getProcessInstanceId())
                    .list();
            // 上一个节点的执行完，再次查询，获取下一个节点的任务信息
            org.activiti.engine.task.Task taskXs = listTaskXs.get(0);
            if(acwfds.get(0).getControlName().equals("审批意见") && acwfds.get(0).getControlValue().equals("通过") && taskXs.getName().equals("Sales Head")){
                //获取所有underwriter 岗位用户名
                variables.put("UW",StringUtils.join(uwUserNames,","));
            }else if(acwfds.get(0).getTaskNodeName().equals("DM") || acwfds.get(0).getTaskNodeName().equals("DMSelect2")){
                //获取所有underwriter 岗位用户名
                variables.put("UW",StringUtils.join(uwUserNames,","));
            }else {
                variables.put("UW","");
            }


            if (hasVariables) {
                //带参数完成任务
                taskRuntime.complete(TaskPayloadBuilder.complete()
                        .withTaskId(taskID)
                        .withVariables(variables)
                        .build());
            } else {
                taskRuntime.complete(TaskPayloadBuilder.complete()
                        .withTaskId(taskID)
                        .build());
            }

            List<org.activiti.engine.task.Task> listTask = taskService.createTaskQuery()
                    .processInstanceId(processInstance.getProcessInstanceId())
                    .list();
/*            if (flag2) {
                for (org.activiti.engine.task.Task task1 : listTask) {
                    if (task1.getName().equals("保险购买确认")) {
                        ActWorkflowFormDataDTO actWorkflowFormDataDTO = new ActWorkflowFormDataDTO();
                        actWorkflowFormDataDTO.setControlId("FormProperty_0a566om");
                        actWorkflowFormDataDTO.setControlType("radio");
                        actWorkflowFormDataDTO.setControlLable("审批意见");
                        actWorkflowFormDataDTO.setControlIsParam("i");
                        actWorkflowFormDataDTO.setControlValue("1");
                        actWorkflowFormDataDTO.setControlDefault("通过--__--驳回");
                        *//*Task taskTemp = taskRuntime.task(task1.getId());
                        ActWorkflowFormData actWorkflowFormData = new ActWorkflowFormData(processInstance.getBusinessKey(), actWorkflowFormDataDTO, taskTemp);
                        acwfds.add(actWorkflowFormData);*//*
             *//*  if (task1.getAssignee() == null) {
                            taskRuntime.claim(TaskPayloadBuilder.claim()
                                    .withTaskId(task1.getId())
                                    .build());
                        }
                        taskRuntime.complete(TaskPayloadBuilder.complete()
                                .withTaskId(task1.getId())
                                .withVariables(variables1)
                                .build());*//*
                        Authentication.setAuthenticatedUserId("165");
                        taskService.complete(task1.getId(),variables1);
                    }
                }
            }*/
            if (flag) {
                for (org.activiti.engine.task.Task task1 : listTask) {
                    if (task1.getName().equals("保证金调整审核")) {
                        Authentication.setAuthenticatedUserId("165");
                        taskService.complete(task1.getId(),variables1);

                    }
                    if (task1.getName().equals("保险购买确认")) {
                        variables1.put("FormProperty_0a566om", 0);
                        ActWorkflowFormDataDTO actWorkflowFormDataDTO = new ActWorkflowFormDataDTO();
                        actWorkflowFormDataDTO.setControlId("FormProperty_0a566om");
                        actWorkflowFormDataDTO.setControlType("radio");
                        actWorkflowFormDataDTO.setControlLable("审批意见");
                        actWorkflowFormDataDTO.setControlIsParam("i");
                        actWorkflowFormDataDTO.setControlValue("1");
                        actWorkflowFormDataDTO.setControlDefault("通过--__--驳回");
                        /*Task taskTemp = taskRuntime.task(task1.getId());
                        ActWorkflowFormData actWorkflowFormData = new ActWorkflowFormData(processInstance.getBusinessKey(), actWorkflowFormDataDTO, taskTemp);
                        acwfds.add(actWorkflowFormData);*/
                        Authentication.setAuthenticatedUserId("165");
                        taskService.complete(task1.getId(),variables1);
                    }
                }
            }
            if (flag1) {
                for (org.activiti.engine.task.Task task1 : listTask) {
                    if (task1.getName().equals("保证金调整确认")) {
                        // variables1.put("FormProperty_1lnclmq", 1);
                        ActWorkflowFormDataDTO actWorkflowFormDataDTO = new ActWorkflowFormDataDTO();
                        actWorkflowFormDataDTO.setControlId("FormProperty_1lnclmq");
                        actWorkflowFormDataDTO.setControlType("radio");
                        actWorkflowFormDataDTO.setControlLable("审批意见");
                        actWorkflowFormDataDTO.setControlIsParam("i");
                        actWorkflowFormDataDTO.setControlValue("1");
                        actWorkflowFormDataDTO.setControlDefault("通过--__--驳回");
                      /*  Task taskTemp = taskRuntime.task(task1.getId());
                        ActWorkflowFormData actWorkflowFormData = new ActWorkflowFormData(processInstance.getBusinessKey(), actWorkflowFormDataDTO, taskTemp);
                        acwfds.add(actWorkflowFormData);*/
                        Authentication.setAuthenticatedUserId("165");
                        taskService.complete(task1.getId(),variables1);
                    }
                    if (task1.getName().equals("保证金调整审核")) {
                        Authentication.setAuthenticatedUserId("165");
                        taskService.complete(task1.getId(),variables1);
                    }
                }
                List<org.activiti.engine.task.Task> listTask3 = taskService.createTaskQuery()
                        .processInstanceId(processInstance.getProcessInstanceId())
                        .list();
                for (org.activiti.engine.task.Task task1 : listTask3) {
                    if (task1.getName().equals("保证金调整审核")) {
                        Authentication.setAuthenticatedUserId("165");
                        taskService.complete(task1.getId(),variables1);

                    }
                }
            }
            List<org.activiti.engine.task.Task> listTask2 = taskService.createTaskQuery()
                    .processInstanceId(processInstance.getProcessInstanceId())
                    .list();
            if (listTask2 != null && listTask2.size() > 0) {

                if (listTask2.size() > 1) {
                    for (org.activiti.engine.task.Task task1 : listTask2) {
                        try {
                            String finalDqjdmc = dqjdmc;
                            ThreadUtil.execute(new Runnable() {

                                @Override
                                public void run() {
                                    sendMail(task1, processInstance.getBusinessKey(), finalDqjdmc);
                                }
                            });
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                } else {
                    // 上一个节点的执行完，再次查询，获取下一个节点的任务信息
                    org.activiti.engine.task.Task task1 = listTask2.get(0);

                    //无下一节点
                    if (task.getFormKey().equals("Activity_02emtf1") && task1 == null) {
                        //当前流程instanceId
                        // 本地资源路径 dealerName
                        Map<String, String> file = actWorkflowFormDataMapper.getFileUrlByInstanceId(businessKey);
                        if (StringUtils.isNotEmpty(file.get("fileUrl"))) {
                            String fileUrl = file.get("fileUrl");
                            String fileName = file.get("dealerName");
                            // 本地资源路径
                            String localPath = RuoYiConfig.getProfile();
                            String downloadPath = "";
                            if (fileUrl.contains("template")) {
                                // 数据库资源地址
                                downloadPath = localPath + fileUrl;
                            } else {
                                String replace = fileUrl.replace("/profile", "");
                                // 数据库资源地址
                                downloadPath = localPath + replace;
                            }

                            //pdf路径
                            String pdfUrl = StrUtil.removeSuffixIgnoreCase(downloadPath, ".docx") + ".pdf";
                            //文件存储路径
                            String storagePdfUrl = StrUtil.removeSuffixIgnoreCase(fileUrl, ".docx") + ".pdf";
                            //文件名
                            String storageName = StrUtil.removeSuffixIgnoreCase(fileName, ".docx") + ".pdf";
                            AsposeUtil.doc2pdf(downloadPath, pdfUrl);

                            actWorkflowFormDataMapper.updateFileUrlByInstanceId(businessKey, storagePdfUrl, storageName);
                        }

                    }
                    //查询提交人
                    String createByName = actWorkflowFormDataMapper.getCreateBy(businessKey);
                    String salesHead = actWorkflowFormDataMapper.getSalesHead(createByName);
                    if (ObjectUtil.isNotEmpty(task1) && StringUtils.isNotEmpty(salesHead) && task1.getName().equals("Sales Head") ) {
                        if(acwfds.get(0).getControlName().equals("审批意见") && acwfds.get(0).getControlValue().equals("通过")){
                            //Sales Head 特殊处理
                            List<String>  dealtUserList = new ArrayList<>();
                            List<String> sales = sysUserMapper.getuwNamesByPostCode("sales head");
                            taskService.deleteCandidateUser(task1.getId(),StringUtils.join(sales,","));
                            String name = SecurityUtils.getLoginUser().getUser().getUserName();
                            // String startNodeByNM = actWorkflowFormDataMapper.getStartNodeByNM(businessKey);
                            if(StringUtils.isNotEmpty(name)){
                                if(name.equals("af175")){
                                    dealtUserList.add("af186");
                                }else if(name.equals("af186")){
                                    dealtUserList.add("af175");
                                }
                            }
                            //设置流程办理人
                            for (String userName : dealtUserList) {
                                taskService.addCandidateUser(task1.getId(),userName);
                                //发送待办邮件
                                sendMailByEmailInfo(sysUserMapper.selectUserByUserName(userName), businessKey,false,task1.getName());
                            }
                        }
                    }

                    Boolean flagUw = false;

                    Boolean zhuanfa = false;

                    for (ActWorkflowFormData acwfd : acwfds) {
                        String controlName = acwfd.getControlName();
                        String controlValue = acwfd.getControlValue();
                        if (controlName.equals("审批意见") && (controlValue.equals("驳回") || controlValue.equals("驳回（DM填完下个节点为Underwriter）") || controlValue.equals("拒绝"))) {
                            flagUw = true;
                        }
                        if (controlName.equals("是否转发") && controlValue.equals("转发")) {
                            zhuanfa = true;
                        }
                    }
                    //TODO 转发缓处理
                    if (zhuanfa) {
                        //获取用户名称
                        String userName = acwfds.get(0).getControlValue();
                        if (StringUtils.isNotEmpty(userName)) {
                            SysUser sysUser = sysUserMapper.selectUserByUserName(userName);
                            if (ObjectUtil.isNotEmpty(sysUser)) {
                                sendMailByEmailInfo(sysUser, businessKey,false,task1.getName());
                            }
                        }
                    }



                    //获取流程发起人
                    String createBy = actWorkflowFormDataMapper.getCreateBy(businessKey);
                    //驳回邮件经手人处理  || task1.getName().equals("OP")
                    if (ObjectUtil.isNotEmpty(task1) && flagUw && (task1.getName().equals("DM") || task1.getName().equals("Underwriter") )) {
                        //驳回 DM UW
                        if(task1.getName().equals("Underwriter")){
                            taskService.deleteCandidateUser(task1.getId(),StringUtils.join(uwUserNames,","));
                        }

                        List<ActWorkflowFormData> actWorkflowFormDataList = new ArrayList<>();
                        //经办人list
                        List<String>  dealtUserList = new ArrayList<>();

                        if (task1.getName().contains("OP")) {
                            actWorkflowFormDataList = actWorkflowFormDataMapper.getOpByBusinessKey(businessKey, task1.getName());
                        }else {
                            actWorkflowFormDataList = actWorkflowFormDataMapper.getUWByBusinessKey(businessKey, task1.getName());
                        }

                        //处理人 用户名
                        List<String> actUserList = actWorkflowFormDataList.stream().map(ActWorkflowFormData::getCreateBy).collect(Collectors.toList());

                        if(CollectionUtil.isNotEmpty(actUserList)){
                            dealtUserList.addAll(actUserList);
                        }

/*                    //DM 判断发起人
                    boolean match = dealtUserList.stream()
                            .noneMatch(user -> (user.equals(createBy)));
                    if(task1.getName().equals("DM")){
                        if(match){
                            //驳回至DM，审批列表为空或发起人不在列表中 发送待办至发起人
                            dealtUserList.add(createBy);
                        }
                    }*/
                        //TODO OP 处理待定
                        else if(task1.getName().equals("OP")){

                        }
                        if(task1.getName().equals("DM")){
                            List<String> dmUserNames = sysUserMapper.getuwNamesByPostCode("dm");
                            dmUserNames.add(createBy);
                            LinkedHashSet<String> hashSet = new LinkedHashSet<>(dmUserNames);
                            System.out.println("本次将任务分给DM"+ hashSet);
                            for (String name : hashSet) {
                                taskService.addCandidateUser(task1.getId(),name);
                            }
                            System.out.println("结束");
                            //发送待办邮件
                            if(StringUtils.isNotEmpty(createBy)){
                                sendMailByEmailInfo(sysUserMapper.selectUserByUserName(createBy), businessKey,false,task1.getName());
                                System.out.println("发送邮件给创建人"+createBy);
                            }
                        }else{
                            //设置流程办理人
                            for (String userName : dealtUserList) {
                                taskService.addCandidateUser(task1.getId(),userName);
                                //发送待办邮件
                                sendMailByEmailInfo(sysUserMapper.selectUserByUserName(userName), businessKey,false,task1.getName());
                            }
                        }

       /*             if(task1.getName().equals("DM") && dealtUserList.size()==0 ){
                        if(createBy.equals("AF569")){
                            taskService.addCandidateUser(task1.getId(),"af504");
                            sendMailByEmailInfo(sysUserMapper.selectUserByUserName("af504"), businessKey,false,task1.getName());
                        }else{
                            taskService.addCandidateUser(task1.getId(),createBy);
                            sendMailByEmailInfo(sysUserMapper.selectUserByUserName(createBy), businessKey,false,task1.getName());
                        }

                    }*/

                    } else {
                        if(task1.getName().equals("合同下载") || task1.getName().equals("合同修改")){
                            //发送待办邮件
                            if(StringUtils.isNotEmpty(createBy)){
                                sendMailByEmailInfo(sysUserMapper.selectUserByUserName(createBy), businessKey,false,task1.getName());
                                System.out.println("子流程发送邮件给创建人"+createBy);
                            }
                        }else{
                            try {
                                String finalDqjdmc1 = dqjdmc;
                                ThreadUtil.execute(new Runnable() {
                                    @Override
                                    public void run() {
                                        sendMail(task1, processInstance.getBusinessKey(), finalDqjdmc1);
                                    }
                                });
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                    }

                }
            }
            if(flag3){
                actWorkflowFormDataMapper.updateAnnualReviewy2(businessKey,DateUtils.getTime());
            }else{
                //修改annaul update时间
                actWorkflowFormDataMapper.updateAnnualReviewy(businessKey,DateUtils.getTime());
            }

            //写入数据库
            return actWorkflowFormDataService.insertActWorkflowFormDatas(acwfds,shouDong);
        }catch (Exception e){
            e.printStackTrace();
            throw  new BaseException(e.getMessage());
        }finally {
            actWorkflowFormDataMapper.deleteActWorkflowLockById(uuid);
        }
    }

    public void sendMail(org.activiti.engine.task.Task task1,String businessKey,String jiedian){
        if (task1 != null) { // 说明有任务
            if(StringUtils.isNotEmpty(jiedian)){
                if(jiedian.equals("保证金调整确认")&&task1.getName().equals("保险购买确认") || jiedian.equals("保险购买确认")&&task1.getName().equals("保证金调整确认")){
                    //不发邮件
                    return;
                }
            }
            System.out.println("下一个的任务节点二：" + task1);
            String taskId = task1.getId();
            System.out.println("下一个的任务节点的taskId： " + taskId);
            if(task1.getName().equals("UW-Requester")){
                //流程9需要给所以信审发送邮件,并标明节点
                ArrayList<String> groups = new ArrayList<>();
                groups.add("underwriter");
                groups.add("supervisor");
                groups.add("credit manager");
                for (String group : groups) {
                    System.out.println("groupId==" + group);
                    // 根据组查对应组成员id，在查到对应的用户对象信息
                    List<SysUser> userList = sysPostMapper.selectUserListByPostCode(group);
                    System.out.println("userList==" + userList.toString());
                    if (userList != null && userList.size() > 0) {
                        for (SysUser sysUser : userList) {
                            log.info("邮件发送，收件人用户为{}",sysUser.getUserName());
                            // 调用发送邮件方法
                            try {
                                sendMailByEmailInfo(sysUser,businessKey,false,task1.getName());
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }

            }
            // 根据 taskId 去 act_ru_integration 表中查询 GROUP_ID_
            ActRuIdentitylink actRuIdentitylink = actRuIdentitylinkMapper.selectActRuIdentitylinkByTaskId(taskId);
            if(task1.getName().equals("Underwriter") || task1.getName().equals("UW-Requester") || task1.getName().equals("UW-Approver")){
                actWorkflowFormDataMapper.updateReport(businessKey,DateUtils.getTime());
                actWorkflowFormDataMapper.updateReportByUw(businessKey,DateUtils.getTime());
                actWorkflowFormDataMapper.updateAnnualReviewy3(businessKey,new Date());
            }
            String groupId = null;
            String userName= null;
            if(ObjectUtil.isEmpty(actRuIdentitylink)){
                groupId = task1.getName();
            }else {
                groupId = actRuIdentitylink.getGroupId();    // 获取组
                userName = actRuIdentitylink.getUserId();    // 获取用户，返回的是用户名
            }

            if (!StringUtil.isEmpty(groupId)) {
                if(groupId.equals("保险购买确认")||groupId.equals("保证金调整确认") ||groupId.equals("盈余保证金操作")){
                    groupId = "op";
                }else if(groupId.equals("保证金调整审核") ||groupId.equals("盈余保证金操作审核") ){
                    groupId = "opManager";
                }else if(groupId.equals("UW-Requester")){
                    groupId = "underwriter";
                }
                System.out.println("groupId==" + groupId);
                // 根据组查对应组成员id，在查到对应的用户对象信息
                List<SysUser> userList = sysPostMapper.selectUserListByPostCode(groupId);
                System.out.println("userList==" + userList.toString());
                if (userList != null && userList.size() > 0) {
                    for (SysUser sysUser : userList) {
                        log.info("邮件发送，收件人用户为{}",sysUser.getUserName());
                        // 调用发送邮件方法
                        try {
                            sendMailByEmailInfo(sysUser,businessKey,false,task1.getName());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            } else {
                if(task1.getName().equals("Underwriter")){
                    List<SysUser> underwriter = sysPostMapper.selectUserListByPostCode("underwriter");
                    for (SysUser sysUser : underwriter) {
                        // 调用发送邮件方法
                        try {
                            sendMailByEmailInfo(sysUser,businessKey,false,task1.getName());
                        } catch (IOException e) {
                            e.printStackTrace();
                            log.error("邮件发送失败{}",e.getMessage());
                        }
                    }
                }else if (!StringUtil.isEmpty(userName)) {
                    System.out.println("userName==" + userName);
                    // 根据user_name查询用户
                    SysUser sysUser = sysUserMapper.selectUserByUserName(userName);
                    System.out.println("sysUser==" + sysUser.toString());
                    if( task1.getName().equals("Credit-Approver") || task1.getName().equals("UW-Approver")){
                        actWorkflowFormDataMapper.updateAnnualReviewy4(businessKey,sysUser.getNickName());
                    }
                    // 调用发送邮件方法
                    try {
                        sendMailByEmailInfo(sysUser,businessKey,false,task1.getName());
                    } catch (IOException e) {
                        log.error("邮件发送失败{}",e.getMessage());
                    }
                }
            }
        }
    }

    @Override
    public Task getById(String taskID) {
        Task task = taskRuntime.task(taskID);
        return task;
    }

    /**
     * 根据流程实例查询下一节点组信息，在发送邮件
     *
     * @param sysUser
     * @throws IOException
     */
    public void sendMailByEmailInfo(SysUser sysUser,String businessKey,boolean flag ,String name) throws IOException {
        int  sendFlag = 0;
        StringBuilder contentStr = new StringBuilder();
        if(isSendEmal!=null && isSendEmal.equals("true")) {
            //申请流程名称
            String str = actWorkflowFormDataMapper.selectByInstanceId(businessKey);

            //经销商名称
            List<Map<String, String>> dealerNames = actWorkflowFormDataMapper.getDealerNameByInstanceId(businessKey);
            String dealerNameTemp = "";
            for (Map<String, String> dealerName : dealerNames) {
                String dealerNameCN = dealerName.get("dealerNameCN");
                if(StringUtils.isNotEmpty(dealerNameCN)){
                    dealerNameTemp =  dealerNameCN;
                }
            }

            String names = "";
            for (Map<String, String> dealerName : dealerNames) {
                if(dealerName!=null){
                    dealerName.values();
                    //获取经销商中英文
                    names = names + "---" + StringUtils.join(dealerName.values(), "---");
                    dealerNameTemp = StringUtils.join(dealerName.values());
                }
            }

            //String content = "网站链接:"+url+"\n|--------|申请流程名称："+str+"\n|----------|经销商名称:"+names;
            String ln = "<br>";

            if(businessKey.contains("WLS")){
                sendFlag =1;
                str = "WFS Limit Set-Up";
                if(!StringUtils.isEmpty(name)){
                    StringBuilder table = new  StringBuilder();
                    name = name+"-"+sysUser.getNickName();
                    String content = msg + ln + "申请流程名称:" + str + ln + "经销商名称：" + names + ln + "申请流程Coding:"+ businessKey +ln +"当前节点为:" + name + ln + "网站链接:" + "<a href ='" + url + "'>点此登录</a>";
                    if(name.contains("UW-Requester")){
                        //查询UW
                        if(StringUtils.isNotEmpty(dealerNameTemp)){
                            String replace = dealerNameTemp.replace("[", "").replace("]", "");
                            String dmName = actWorkflowFormDataMapper.getUWByDealerName(replace);
                            if(StringUtils.isNotEmpty(dmName)){
                                name = "UW-Requester - "+dmName;
                            }else{
                                name = "UW-Requester" ;
                            }
                            content = msg + ln + "申请流程名称:" + str + ln + "经销商名称：" + names + ln + "申请流程Coding:"+ businessKey +ln +"当前节点为:" + name + ln + "网站链接:" + "<a href ='" + url + "'>点此登录</a>";
                        }
                        table.append("<html><head></head><body><h3>LIMIT SET-UP PROPOSAL</h3>");
                        table.append("<table border=\"5\" style=\"border:solid 1px #E8F2F9;font-size:16px;\">");
                        table.append("<tr style=\"background-color: #428BCA; color:#ffffff\"><th>Dealer</th><th>Sector</th><th>Limit Type</th><th>CurrentCreditLimit</th><th>CurrentActiveLimit</th><th>CurrentActiveLimitExpiryDate</th><th>CurrentDeposit%</th><th>Current O/S</th><th>ProposedActiveLimit</th></tr>");
                        //构造表格
                        List<Map<String, Object>> limitMap = actWorkflowFormDataMapper.getLimit(businessKey);
                        for (Map<String, Object> stringStringMap : limitMap) {
                            table.append("<tr>");
                            table.append("<td>" + stringStringMap.get("dealerName")+ "</td>");
                            table.append("<td>" + stringStringMap.get("sector")+ "</td>");
                            table.append("<td>" + stringStringMap.get("limitType")+ "</td>");
                            //格式化
                            Object currentCreditLimit = stringStringMap.get("CurrentCreditLimit");
                            if(currentCreditLimit!=null ){
                                BigDecimal amt = new BigDecimal(currentCreditLimit.toString());
                                String currentCredit = NumberFormat.getNumberInstance().format(amt);
                                table.append("<td>" + currentCredit + "</td>");
                            }else{
                                table.append("<td>" + " "+ "</td>");
                            }

                            //格式化
                            Object CurrentActiveLimit = stringStringMap.get("CurrentActiveLimit");
                            if(CurrentActiveLimit!=null && !CurrentActiveLimit.toString().equals("")) {
                                BigDecimal amt = new BigDecimal(CurrentActiveLimit.toString());
                                String CurrentActive = NumberFormat.getNumberInstance().format(amt);
                                table.append("<td>" + CurrentActive+ "</td>");
                            }else{
                                table.append("<td>" + " "+ "</td>");
                            }

                            //格式化
                            Object currentActiveLimitExpiryDate = stringStringMap.get("currentActiveLimitExpiryDate");
                            if(currentActiveLimitExpiryDate!=null){
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                                String format = sdf.format(currentActiveLimitExpiryDate);
                                table.append("<td>" + format+ "</td>");
                            }else{
                                table.append("<td>" + " "+ "</td>");
                            }

                            //格式化
                            Object approvedCashDeposit = stringStringMap.get("approvedCashDeposit");
                            if(approvedCashDeposit!=null){
                                table.append("<td>" + approvedCashDeposit+ "</td>");
                            }else{
                                table.append("<td>" + " "+ "</td>");
                            }

                            //格式化
                            Object os = stringStringMap.get("os");
                            if(os!=null){
                                BigDecimal amt = new BigDecimal(os.toString());
                                String osAmt = NumberFormat.getNumberInstance().format(amt);
                                table.append("<td>" + osAmt+ "</td>");
                            }else{
                                table.append("<td>" + " "+ "</td>");
                            }

                            //格式化
                            Object proposalActiveLimit = stringStringMap.get("proposalActiveLimit");
                            if(proposalActiveLimit!=null){
                                String proposalActive = proposalActiveLimit.toString().replace(",", "");
                                BigDecimal proposalActiveAmt = new BigDecimal(proposalActive.toString());
                                String amt = NumberFormat.getNumberInstance().format(proposalActiveAmt);
                                table.append("<td>" + amt+ "</td>");
                            }else{
                                table.append("<td>" + " "+ "</td>");
                            }
                            table.append("</tr>");
                        }
                        table.append("</table>");
                        table.append("</body></html>");
                    }else if(name.equals("UW-Approver")){
                        sendFlag = 2;
                    }
                    contentStr.append(content);
                    contentStr.append(ln);
                    contentStr.append(table);
                }
            }else{
                String content = msg + ln + "申请流程名称:" + str + ln + "经销商名称：" + names + ln + "网站链接:" + "<a href ='" + url + "'>点此登录</a>";
                contentStr.append(content);
            }
            // 获取邮箱
            String email = sysUser.getEmail();
            if (!StringUtil.isEmpty(email)) {
                try {
                    String title = "";
                    // 测试文本邮件发送（无附件）
                    String to = email;
                    if(sendFlag == 1){
                        title = "WWS- WFS Limit Set-Up-"+names;
                    }else  if (sendFlag == 2){
                        title = "WWS- WFS Limit Set-Up-"+names+"-Approver";
                    }else{
                        title = "您有待办任务请审批";
                    }

                    //带附件方式调用
                    new EmailUtil(from, mailSender).sendMessageCarryFiles(to, title, contentStr.toString(), null);
                    // return AjaxResult.success();
                } catch (Exception e) {
                    log.error("邮件发送失败{}",e.getMessage());
                }
            }
        }
    }

}
